﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace Client
{
    public class Program
    {
        public static Socket tcpClient;
        public static void Main(string[] args)
        {

            tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            ConnectSocket();

            Thread thread = new Thread(Monitor);
            thread.IsBackground = true;
            thread.Start();
            while (true)
            {
                if (tcpClient == null)
                {
                    break;
                }
                else
                {
                    string str = Console.ReadLine();
                    ProcessMessage(str);
                }

            }
        }
        /// <summary>
        /// 连接服务器
        /// </summary>
        public static void ConnectSocket()
        {
            Console.WriteLine("请输入正确的服务器局域网ip!");
            while (true)
            {
                try
                {
                    string serverIp = Console.ReadLine();
                    IPAddress opAddress = IPAddress.Parse(serverIp);
                    IPEndPoint point = new IPEndPoint(opAddress, 6789);
                    tcpClient.Connect(point);//通过Ip，和端口号定位服务器。
                    Console.WriteLine("服务器连接成功\n输入格式如下:\n私聊:Name|内容\n广播:All|内容");
                    break;
                }
                catch
                {
                    Console.WriteLine("连接失败，请确保服务器开启，及服务器IP地址正确");
                }
            }

        }
        public static void Send(Socket socket, string value)
        {
            //把字符传变成流
            byte[] recByte = Encoding.UTF8.GetBytes(value);
            //发送给客户端
            socket.Send(recByte);
        }
        /// <summary>
        /// 接收消息
        /// </summary>
        public static void Monitor()
        {
            while (tcpClient != null)
            {
                try
                {
                    byte[] strs = new byte[(2048 * 2048)];
                    int a = tcpClient.Receive(strs);
                    string str = Encoding.UTF8.GetString(strs, 0, a);
                    Console.WriteLine(str);
                }
                catch
                {
                    Console.WriteLine("服务器已关闭,断开服务器连接");
                    break;
                }

            }
        }
        public static void ProcessMessage(string str)
        {

            string[] strs = str.Split(',');
            if (strs.Length > 2)
            {
                Console.WriteLine("输入不合法");
                return;
            }
            Send(tcpClient, str);
        }
    }


}